package GUI;

import CDB.Categorias;
import CDB.Detallesubcategoria;
import CDB.Subcategoria;
import Negocios.ControlCategories;
import Negocios.ControlSubcategory;
import Negocios.ControlSubcategoryDetail;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 *
 * @author ISCErick
 */
public class AgregarCategoria extends javax.swing.JInternalFrame {

    String Accion = "";
    Categorias categoria = null;

    public AgregarCategoria() {
        initComponents();
    }

    AgregarCategoria(Categorias categoria, String editar) {
        initComponents();
        this.Accion = editar;
        this.categoria = categoria;
        txtNombre.setText(categoria.getNombre());
        jrbSi.setSelected(true);
        llenarSubcategorias();
        marcaSubcategorias();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jrbGrupo = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jrbSi = new javax.swing.JRadioButton();
        jrbNo = new javax.swing.JRadioButton();
        panSubcategorias = new javax.swing.JPanel();
        jspSubcaegoria = new javax.swing.JScrollPane();
        panSubcat = new javax.swing.JPanel();
        btnCancelar = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();

        setTitle("Agregar nueva categoria");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/category.png"))); // NOI18N

        jLabel1.setText("En esta ventana podra dar de alta nuevas categorias.");

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/category.png"))); // NOI18N

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        jLabel3.setText("Nombre de la categoria:");

        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreKeyTyped(evt);
            }
        });

        jLabel4.setText("¿Tendra subcategorias?");

        jrbGrupo.add(jrbSi);
        jrbSi.setText("Si");
        jrbSi.setOpaque(false);
        jrbSi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbSiActionPerformed(evt);
            }
        });

        jrbGrupo.add(jrbNo);
        jrbNo.setSelected(true);
        jrbNo.setText("No");
        jrbNo.setOpaque(false);
        jrbNo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbNoActionPerformed(evt);
            }
        });

        panSubcategorias.setBackground(new java.awt.Color(255, 255, 255));
        panSubcategorias.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Subcategorias disponibles", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, new java.awt.Color(0, 153, 0)));

        panSubcat.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout panSubcatLayout = new javax.swing.GroupLayout(panSubcat);
        panSubcat.setLayout(panSubcatLayout);
        panSubcatLayout.setHorizontalGroup(
            panSubcatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 367, Short.MAX_VALUE)
        );
        panSubcatLayout.setVerticalGroup(
            panSubcatLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 180, Short.MAX_VALUE)
        );

        jspSubcaegoria.setViewportView(panSubcat);

        javax.swing.GroupLayout panSubcategoriasLayout = new javax.swing.GroupLayout(panSubcategorias);
        panSubcategorias.setLayout(panSubcategoriasLayout);
        panSubcategoriasLayout.setHorizontalGroup(
            panSubcategoriasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jspSubcaegoria)
        );
        panSubcategoriasLayout.setVerticalGroup(
            panSubcategoriasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jspSubcaegoria, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(panSubcategorias, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtNombre, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jrbSi)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jrbNo)))
                        .addGap(0, 266, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jrbSi)
                    .addComponent(jrbNo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panSubcategorias, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/Cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/save.png"))); // NOI18N
        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnCancelar, btnGuardar});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnGuardar)
                    .addComponent(btnCancelar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        try {
            this.setClosed(true);
            System.gc();
        } catch (PropertyVetoException ex) {
            this.dispose();
            System.gc();
        }
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void jrbSiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbSiActionPerformed
        if (txtNombre.getText().equals("")) {
            JOptionPane.showMessageDialog(this,
                    "Introdusca el nombre de la categoria",
                    "Falta nombre de categoria", 2);
            jrbNo.setSelected(true);
            txtNombre.requestFocus();
        } else {
            panSubcat.removeAll();
            panSubcat.setVisible(false);
            panSubcat.setVisible(true);
            llenarSubcategorias();
            marcaSubcategorias();
        }
    }//GEN-LAST:event_jrbSiActionPerformed

    private void jrbNoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbNoActionPerformed
        panSubcat.removeAll();
        panSubcat.setVisible(false);
        panSubcat.setVisible(true);
    }//GEN-LAST:event_jrbNoActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        try {
            ControlCategories cc = new ControlCategories();
            if (Accion.equals("Editar")) {
                ControlSubcategoryDetail csd = new ControlSubcategoryDetail();
                //si esta libre
                if (jrbNo.isSelected()) {
                    //Actualiza la lista
                    csd.deleteByIdCategoria(categoria.getIdcategoria());
                    csd.add(categoria, null);
                    //Altero el objeto
                    categoria.setSubcategorias(false);
                    //Lo actualizo
                    cc.update(categoria, categoriasSeleccionadas());
                } else if (jrbSi.isSelected()) {
                    categoria.setSubcategorias(true);
                    //Actualiza la lista
                    csd.deleteByIdCategoria(categoria.getIdcategoria());
                    cc.update(categoria, categoriasSeleccionadas());
                }
                JOptionPane.showMessageDialog(this, "Categoria guardada con exito", "Guardado", 1);
                try {
                    this.setClosed(true);
                    System.gc();
                } catch (PropertyVetoException ex) {
                    this.dispose();
                    System.gc();
                }
            } else {
                //Comprobar si el nombre de la categoria que pretendemos guardar
                //esta libre
                if (cc.categoryExist(txtNombre.getText())) {
                    //no esta libre
                    JOptionPane.showMessageDialog(this, "Ya existe una categoria con el nombre '" + txtNombre.getText() + "'."
                            + "\n" + "Cambie el nombre para poder agregar una nueva categoria.", "Ya existe esta categoria",
                            0);
                    txtNombre.requestFocus();
                    clearFields();
                } else {
                    //si esta libre
                    if (jrbNo.isSelected()) {
                        cc.add(txtNombre.getText(), false);
                    } else if (jrbSi.isSelected()) {
                        cc.add(txtNombre.getText(), true, categoriasSeleccionadas());
                    }
                    JOptionPane.showMessageDialog(this, "Categoria guardada con exito", "Guardado", 1);
                    clearFields();
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error: " + e, "Ha ocurrido un error", 0);
        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void txtNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyTyped
        if (txtNombre.getText().length() > 24) {
            evt.consume();
            JOptionPane.showMessageDialog(this, "Solo se permite un largo maximo"
                    + " de 25 letras en este campo.", "Maximo de letras alcanzado", 0);
        }
    }//GEN-LAST:event_txtNombreKeyTyped

    private List categoriasSeleccionadas() {
        List<String> subcategorias = new ArrayList<>();
        int numSubcat = panSubcat.getComponentCount();

        for (int i = 0; i < numSubcat; i++) {
            JPanel panel = (JPanel) panSubcat.getComponent(i);
            JCheckBox chk = (JCheckBox) panel.getComponent(1);
            if (chk.isSelected()) {
                JLabel label = (JLabel) panel.getComponent(2);
                subcategorias.add(label.getText());
            }
        }
        return subcategorias;
    }

    private void llenarSubcategorias() {
        List subcat = null;
        panSubcat.setVisible(false);
        panSubcat.setLayout(new GridLayout(0, 3, 3, 3));
        //Revisa si la accion es editar
        ControlSubcategory csc = new ControlSubcategory();
        subcat = csc.selectAll();
        for (int i = 0; i < subcat.size(); i++) {
            Subcategoria sub = (Subcategoria) subcat.get(i);
            panSubcat.add(formarSubcategoria(sub, i));
        }
        panSubcat.setVisible(true);
    }

    private List subcategoriasEncontradas() {
        List<String> subcategorias = new ArrayList<>();
        int numSubcat = panSubcat.getComponentCount();
        for (int i = 0; i < numSubcat; i++) {
            JPanel panel = (JPanel) panSubcat.getComponent(i);
            JLabel label = (JLabel) panel.getComponent(2);
            subcategorias.add(label.getText());
        }
        return subcategorias;
    }

    private void marcaSubcategorias() {
        ControlSubcategoryDetail csd = new ControlSubcategoryDetail();
        ControlSubcategory cs = new ControlSubcategory();
        List detSubCat = csd.selectByIdCategoria(categoria.getIdcategoria());
        List subcatAnteriores = subcategoriasEncontradas();
        for (int i = 0; i < detSubCat.size(); i++) {
            Detallesubcategoria detalle = (Detallesubcategoria) detSubCat.get(i);
            for (int j = 0; j < subcatAnteriores.size(); j++) {
                JPanel panel = (JPanel) panSubcat.getComponent(j);
                JLabel label = (JLabel) panel.getComponent(2);
                Subcategoria subcategoria = cs.selectOne(Integer.parseInt(label.getText()));
                if (detalle.getSubcategoria().getNombre().equals(subcategoria.getNombre())) {
                    JCheckBox chk = (JCheckBox) panel.getComponent(1);
                    chk.setSelected(true);
                }
            }
        }
    }

    private void clearFields() {
        txtNombre.setText("");
        jrbNo.setSelected(true);
        panSubcat.removeAll();
        panSubcat.repaint();
        txtNombre.requestFocus();
    }

    private JPanel formarSubcategoria(Subcategoria sub, int index) {
        JPanel subcat;
        subcat = new JPanel(new BorderLayout());

        JLabel nombre = new JLabel(sub.getNombre());
        JLabel id = new JLabel(sub.getIdsubcategoria().toString());
        JCheckBox activa = new JCheckBox("Activar", false);

        id.setVisible(false);
        activa.setForeground(Color.WHITE);
        activa.setName("chk" + index);
        activa.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        nombre.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        nombre.setForeground(Color.WHITE);

        subcat.add(nombre, BorderLayout.NORTH);
        subcat.add(activa, BorderLayout.SOUTH);
        subcat.add(id, BorderLayout.CENTER);
        subcat.setBackground(new java.awt.Color(0, 150, 0));

        return subcat;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.ButtonGroup jrbGrupo;
    private javax.swing.JRadioButton jrbNo;
    private javax.swing.JRadioButton jrbSi;
    private javax.swing.JScrollPane jspSubcaegoria;
    private javax.swing.JPanel panSubcat;
    private javax.swing.JPanel panSubcategorias;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables
}
